package com.example.fmgidsprototype;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.example.fmgidsprototype.data.DataManager;
import com.example.fmgidsprototype.data.VenueCategoryKey;
import com.example.fmgidsprototype.model.Category;
import com.example.fmgidsprototype.model.Venue;
import com.example.fmgidsprototype.model.VenueLocation;

public class JsonReader {
	
	private BufferedReader bufferedReader;
	private FileReader fileReader;
	private InputStream stream;
	private String jsonString;
	private FmGidsPrototypeApp app;
	private DataManager dm;
	
	public JsonReader(InputStream stream, DataManager dm){
		this.stream = stream;
		this.dm = dm;
	}
	
	private String readFile(){
		String line = null;
		StringBuilder sb = new StringBuilder();
		bufferedReader = null;
		fileReader = null;

		try{
			bufferedReader = new BufferedReader(new InputStreamReader(stream));
			while((line = bufferedReader.readLine()) != null){
				sb.append(line + "\n");
			}
		}
		catch(IOException ioe){
			ioe.printStackTrace();
		}
		return sb.toString();
	}
	
	public void writeToDb(){
		JSONObject jObject = null;
		List<Category> catList = new ArrayList<Category>();
		try{
			jObject = new JSONObject(this.readFile());
			//first get all categories
			JSONArray catsArray = jObject.getJSONArray("category");
			//now pick them one by one and for each one...
			for(int i = 0; i < catsArray.length(); i++){
				JSONObject catObject = catsArray.getJSONObject(i);
				//create model object
				Category currentCat = new Category(
					catObject.getString("name"),
					catObject.getString("description"),
					catObject.getString("iconName")
				);
				//make dataobject to store venues
				Set<Venue> venueSet = new HashSet<Venue>();
				//get venues for this cat
				JSONArray venueArray = catObject.getJSONArray("venues");
				for(int j = 0; j < venueArray.length(); j++){
					//for each of them...
					JSONObject venueObject = venueArray.getJSONObject(j);
					//create model object
					Venue currentVenue = new Venue(
						venueObject.getLong("jsonId"),
						venueObject.getString("name"),
						venueObject.getString("description"),
						venueObject.getString("address"),
						venueObject.getString("thumbName"),
						venueObject.getString("picUrl"),
						venueObject.getString("url"),
						venueObject.getString("email"),
						venueObject.getString("phone"),
						venueObject.getString("audioPath")
					);
					//store rating
					int rating = venueObject.getInt("rating");
					currentVenue.setRating(rating);
					//store location data
					currentVenue.setLatitude(venueObject.getDouble("latitude"));
					currentVenue.setLongitude(venueObject.getDouble("longitude"));
					currentVenue.setDistanceFromZero(venueObject.getDouble("distanceFromZero"));
					//add object to dataobject
					venueSet.add(currentVenue);
				}
				//we've got all venues for this cat, let's store the dataobject in the cat object
				currentCat.setVenues(venueSet);
				//store current cat in list
				catList.add(currentCat);
			}
		}
		catch(JSONException jse){
			jse.printStackTrace();
		}
		//now let's write this shit to the db!
		for(Category category : catList){
			//first store category
			long catId;
			if((catId = dm.updateCategory(category)) <= 0)
				catId = dm.saveCategory(category);
			//iterate over venues for this cat
			Iterator<Venue> it = category.getVenues().iterator();
			//for each one...
			while(it.hasNext()){
				
				Venue v = it.next();
				//store it
				long id;
				if((id = dm.updateVenue(v)) <= 0)
					id = dm.saveVenue(v);
				//store the location of the venue if it is a new venue
				VenueLocation venueLocation = new VenueLocation(
							id, v.getLongitude(), v.getLatitude(), v.getDistanceFromZero());
					if(dm.updateVenueLocation(venueLocation) <= 0)
						dm.saveVenueLocation(venueLocation);
				VenueCategoryKey key = new VenueCategoryKey(id, catId);
				if(dm.updateKey(key) <= 0)
					dm.saveKey(key);
			}
		}
	}
	
}
